<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2014 http://minmindai.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: vion77 <8yong8@163.com>
// +----------------------------------------------------------------------

namespace Think\Upload\Driver;
use OSS\Core\OssException;//不然OssException 报错
class AliOss {
    /**
     * 上传文件根目录
     * @var string
     */
    private $rootPath;

    /**
     * 本地上传错误信息
     * @var string
     */
    private $error = ''; //上传错误信息

    /**
     * 对象
     * @var resource
     */
    private $oss_obj;

    private $Timeout = 10;  //上传超时时间

    private $ConnectTimeout = 5;//链接超时时间

    private $config = array(
        'accessKeyId'     => 'LTAI5tHcWHAqyZGdtGphFjPw', 
        'accessKeySecret'     => '2WeDYe2pfU9MTHbqQ3P3tMmKS2bwq8',
        'endpoint'  => 'oss-cn-beijing.aliyuncs.com', //OSS数据中心访问域名
        'bucket' => 'wages-zymaimai', //oss中的文件上传空间
    );

    /**
     * 构造函数，用于设置上传根路径
     * @param array  $config FTP配置
     */
    public function __construct($config){

        //默认配置

        if($config){
            $this->config = array_merge($this->config, $config);
        }else{
            $aliyun_oss = C('aliyun_oss');
            $baset_oss=M("baset_oss");
            $info=$baset_oss->find();
            $this->config['accessKeyId'] = $info['accessKeyId'];
            $this->config['accessKeySecret'] = $info['accessKeySecret'];
            $this->config['endpoint'] =$info['endpoint'];
            $this->config['bucket'] = $info['bucket'];
        }
        vendor('alioss.autoload');
        $accessKeyId = $this->config['accessKeyId'];//去阿里云后台获取秘钥
        $accessKeySecret = $this->config['accessKeySecret'];//去阿里云后台获取秘钥
        $endpoint = $this->config['endpoint'];//你的阿里云OSS地址
        $ossClient = new \OSS\OssClient($accessKeyId, $accessKeySecret, $endpoint);
        $this->oss_obj = $ossClient;
    }

    /**
     * 检测上传根目录
     * @param string $rootpath   根目录
     * @return boolean true-检测通过，false-检测失败
     */
    public function checkRootPath(){
        $result = $this->oss_obj->doesBucketExist($this->config['bucket']); 
        if(!$result){
            $this->error = '上传根目录不存在！';
            return false;
        }
        return true;
    }

    /**
     * 检测上传目录
     * @param  string $savepath 上传目录
     * @return boolean          检测结果，true-通过，false-失败
     */
    public function checkSavePath($savepath){
       return true;
    }

    /**
     * 保存指定文件
     * @param  array   $file    保存的文件信息
     * @param  boolean $replace 同名文件是否覆盖
     * @return boolean          保存状态，true-成功，false-失败
     */
    public function save($file, $replace=true) {
        $ossClient = $this->oss_obj;
        $ossClient->setTimeout($this->Timeout);
        $ossClient->setConnectTimeout($this->ConnectTimeout);
        $filename = $file['tmp_name']!=$file['savename'] ? $file['tmp_name'] : getcwd().'/'.$file['tmp_name'];//本地保存路径

        if(!file_exists($filename)){
            $this->error = '原文件不存在';
            return false;            
        }
        //echo $filename.'/233';exit;
        $object = $file['savepath'] . $file['savename'];//想要保存文件的名称
        //var_dump($filename);var_dump($object);//var_dump($ossClient);exit;
        try{
            $r = $ossClient->uploadFile($this->config['bucket'],$object,$filename);
            //var_dump($r);exit;
            //上传成功，自己编码
        //这里可以删除上传到本地的文件。unlink（$file）；
        } catch(OssException $e) {
            //var_dump($e->getMessage());exit;
            //上传失败，自己编码
            $this->error = $e->getMessage();
            return false;
        }
        return true;
    }

    /**
     * 原有文件直接上传
     * @param  array   $file    保存的文件信息
     * @param  boolean $replace 同名文件是否覆盖
     * @return boolean          保存状态，true-成功，false-失败
     */
    public function direct($from_file, $to_file){
        $ossClient = $this->oss_obj;
        $ossClient->setTimeout($this->Timeout);
        $ossClient->setConnectTimeout($this->ConnectTimeout);
        if (preg_match('/http(s?):\/\/[\w.]+[\w\/]*[\w.]*\??[\w=&\+\%]*/is',$url)){
            if(!file_exists($from_file)){
                $this->error = '原文件不存在';
                return false;            
            }
        }

        $object = $to_file;
        try{
            $r = $ossClient->uploadFile($this->config['bucket'],$object,$from_file);
        } catch(OssException $e) {
            //上传失败，自己编码
            $this->error = $e->getMessage();
            return false;
        }
        return true;
    
    }

    /**
     * 创建目录
     * @param  string $savepath 要创建的目录
     * @return boolean          创建状态，true-成功，false-失败
     */
    public function mkdir($savepath){
        return true;
        $dir = $this->rootPath . $savepath;
        if(ftp_chdir($this->link, $dir)){
            return true;
        }

        if(ftp_mkdir($this->link, $dir)){
            return true;
        } elseif($this->mkdir(dirname($savepath)) && ftp_mkdir($this->link, $dir)) {
            return true;
        } else {
            $this->error = "目录 {$savepath} 创建失败！";
            return false;
        }
    }

    //删除图片
    function fdel($object){
        $preg = "/^http(s)?:\\/\\/.+/";
        if(preg_match($preg,$object)){
            $object =  str_ireplace(C('Wimgurl').'/','',$object);//完整url
        }else{
            $object =  $object;
        }
        //dump($object);exit;
        vendor('alioss.autoload');
        $accessKeyId = C('OssKeyId');//去阿里云后台获取秘钥
        $accessKeySecret = C('OssKeySecret');//去阿里云后台获取秘钥
        $endpoint = C('OssEndpoint');//你的阿里云OSS地址
        $bucket = C('OssBucket');
        $ossClient = new \OSS\OssClient($accessKeyId, $accessKeySecret, $endpoint);
        $exist = $ossClient->doesObjectExist($bucket, $object);
        if($exist){
            $r = $ossClient->deleteObject($bucket, $object);
        }
        return true;    
    }

    /**
     * 获取最后一次上传错误信息
     * @return string 错误信息
     */
    public function getError(){
        return $this->error;
    }

    /**
     * 析构方法，用于断开当前FTP连接
     */
    public function __destruct() {
        //ftp_close($this->link);
    }

}
